package com.solar.etl.util;

public class ClassStack extends SecurityManager {
	static int m_iIdxThis = -1;

	ClassStack() {
		if (m_iIdxThis >= 0)
			return;

		Class[] stack = getClassContext();
		Class c = getClass();
		for (int i = 0; i < stack.length; ++i)
			if (stack[i].equals(c)) {
				m_iIdxThis = i;
				return;
			}
	}

	Class<?>[] getStackNotStatic() {
		Class[] totalStack = getClassContext();
		Class[] subStack = new Class[totalStack.length - 2 - m_iIdxThis];

		for (int i = 2 + m_iIdxThis; i < totalStack.length; ++i)
			subStack[(i - 2 - m_iIdxThis)] = totalStack[i];

		return subStack;
	}

	Class<?> getClassNoStatic(int level) {
		Class[] totalStack = getClassContext();

		if (totalStack.length < 2 + level + m_iIdxThis)
			return null;

		return totalStack[(1 + level + m_iIdxThis)];
	}

	public Class<?> getExternalCallerClassNoStatic(String strCurrPackage) {
		Class[] totalStack = getClassContext();

		if (totalStack.length < 3)
			return null;

		for (int i = 2; i < totalStack.length; ++i)
			if (!(totalStack[i].getName().startsWith(strCurrPackage)))
				return totalStack[i];

		return null;
	}

	public Class<?> getExternalCallerClassNoStatic(String[] arrCurrPackage) {
		Class[] totalStack = getClassContext();

		if (totalStack.length < 3) {
			return null;
		}

		for (int i = 2; i < totalStack.length; ++i) {
			for (int j = 0; j < arrCurrPackage.length; ++j) {
				if (totalStack[i].getName().startsWith(arrCurrPackage[j]))
					break;
				if (j >= arrCurrPackage.length)
					return totalStack[i];

			}
		}

		return null;
	}

	public static Class<?>[] getStack() {
		return new ClassStack().getStackNotStatic();
	}

	public static Class<?> getClass(int level) {
		return new ClassStack().getClassNoStatic(level + 1);
	}

	public static Class<?> getCurrClass() {
		return new ClassStack().getClassNoStatic(1);
	}

	public static Class<?> getCallerClass() {
		return new ClassStack().getClassNoStatic(2);
	}

	public static Class<?> getExternalCallerClass() {
		String[] arr = { "sun.", "java.", "javax.", "com.icebean.core." };

		return new ClassStack().getExternalCallerClassNoStatic(arr);
	}

	public static Class<?> getExternalCallerClass(String pkgName) {
		String[] arr = { "sun.", "java.", "javax.", pkgName };

		return new ClassStack().getExternalCallerClassNoStatic(arr);
	}
}
